package com.example;

import com.alibaba.fastjson.JSON;
import lombok.val;
import org.apache.kafka.clients.consumer.CommitFailedException;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

import java.time.Duration;
import java.util.Collections;
import java.util.Properties;

public class ConsumerImpl implements Consumer {
    private final KafkaConsumer<String, String> consumer;
    private final String topic = "test32";

    public ConsumerImpl() {
        consumer = new KafkaConsumer<>(props());
    }

    @Override
    public void consumerOrder() {
        consumer.subscribe(Collections.singleton(topic));

        try {
            while (true) {
                ConsumerRecords<String, String> records = consumer.poll(Duration.ofSeconds(1));

                for (ConsumerRecord<String, String> r : records) {
                    Order order = JSON.parseObject(r.value(), Order.class);
                    System.out.println(" order = " + order);
                }
            }
        } catch (CommitFailedException ex) {
            ex.printStackTrace();
        } finally {
            try {
                consumer.commitSync();
            } catch (Exception e) {
                consumer.close();
            }
        }
    }

    private Properties props() {
        Properties props = new Properties();
        props.put("group.id", "topic-bay");
        props.put("bootstrap.servers", "localhost:9001");
        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        return props;
    }
}
